import React, { memo, useState, useCallback, useRef, useEffect } from "react";

import classnames from "classnames";

import { Slider } from "antd";

import { PlayerWrap, Control } from "./style";

import { formalMinuteSeconds } from "@/utils/formatMinuteSecond";
import {
  getPlayUrl,
  getSizeImage,
  getMinSecondMsecond,
} from "@/utils/format-utils";

export default memo(function Player(props) {
  const [time, newTime] = useState(0); //正在播放时间
  const [progress, setProgress] = useState(0); //进度条
  const [isPlaying, setIsPlaying] = useState(false); //是否播放
  const [isChanging, setIdChanging] = useState(0); //是否改变
  const [playId, setPlayId] = useState(0); //播放ID hover
  const [clickId, setClickId] = useState(0); //播放按钮
  const [scrolHeight, setScrolHeight] = useState(732); //高度
  const [as, setAs] = useState(0);
  const [showSongList, setShowSongList] = useState(false);
  const [record, setRecord] = useState(0);

  const audioRef = useRef();
  const listbdRef = useRef();
  const scrollRef = useRef(); //ref都是用来测量滚动条

  useEffect(() => {
    if (props.playLists.length) {
      audioRef.current.src = getPlayUrl(props.playerLists.id);
      if (audioRef.current.src.indexOf("undefined") == -1) {
        audioRef.current
          .play()
          .then((res) => {
            setIsPlaying(true);
          })
          .catch((err) => {
            setIsPlaying(false);
          });
      }
    }
  }, [props.times, props.playerLists.id]); // eslint-disable-line react-hooks/exhaustive-deps

  const pLength =
    playId === 0
      ? ""
      : props.lyricText.length !== 0
      ? listbdRef.current.clientHeight - 219
      : "";

  useEffect(() => {
    //每个歌词的时间戳
    if (playId) {
      const datasetId = Array.from(listbdRef.current.children).map(
        (itemp, indexp) => {
          return itemp.dataset.id;
        }
      );
    }
  }, [playId]);

  const timeUpdate = (e) => {
    //当播放器启动时执行函数
    newTime(e.target.currentTime);
    setProgress(((time * 1000) / props.times) * 100);
    const abc = listbdRef.current.children;
    var arr = Object.getOwnPropertyNames(abc);
    var valArr = arr.map(function (i) {
      return abc[i];
    });
    let newArr = valArr.filter((value, index) => {
      return (time * 1000).toFixed(0) - value.dataset.id >= 0;
    });

    const arrLength = newArr.length;

    if (arrLength == newArr.dataset.index) {
      flash = true;
    }
    if (newArr.length) {
      if (record !== arrLength) {
        for (let i = 0; i < valArr.length; i++) {
          valArr[i].className = "lyric";
        }
        changeClassName(newArr, arrLength);
        setRecord(arrLength);
      }
    } else {
      scrollRef.current.scrollTop = 0;
    }
  };

  // props.times这个歌的时间,time正在播放的时间
  useEffect(() => {
    if (formalMinuteSeconds(time * 1000) === formalMinuteSeconds(props.times)) {
      if (props.arrId.length !== 0) {
        // indexId:播放完这一首歌找个这首歌的索引值
        const indexId = props.arrId.indexOf(playId);
        if (props.arrId[indexId + 1] != undefined) {
          // setPlayId 设置下一首歌的播放ID
          // setClickId 为设置左边样式
          setPlayId(props.arrId[indexId + 1]);
          setClickId(props.arrId[indexId + 1]);
          newTime(0);
        } else {
          // 如果没有就默认播放第一首歌
          setPlayId(props.arrId[0]);
          setClickId(props.arrId[0]);
          newTime(0);
        }
      }
    }
  }, [time, playId, props.times, props.arrId]);

  // (playId)

  const changeClassName = (newArr, arrLength) => {
    newArr[newArr.length - 1].className = "lyric whiteSong";
    const a = newArr.map((item, index) => {
      return item.scrollHeight;
    });
    if (as !== arrLength) {
      // eslint-disable-next-line no-eval
      setIdChanging(eval(a.join("+")));
      scrollRef.current.scrollTop =
        progress * 0.01 * pLength - 110 < 0 ? 0 : isChanging - 110;
    }
    setAs(newArr.length);
  };

  const sliderChange = useCallback(
    (value) => {
      // 当进度条改变执行函数
      const pointTime = ((value / 100) * props.times) / 1000;
      audioRef.current.currentTime = pointTime;
    },
    [props.times]
  );

  const play = useCallback(() => {
    //点击播放
    setIsPlaying(!isPlaying);
    isPlaying
      ? audioRef.current.pause()
      : audioRef.current.play().catch((err) => {
          setIsPlaying(false);
        });
    // (isPlaying)
  }, [isPlaying]);

  const checkShowSongList = () => {
    setShowSongList(!showSongList);
  };
  const mouseClick = (id) => {
    setPlayId(id);
    setClickId(id);
    props.playIdChange(id);
  };

  const listbd = (e) => {
    //点击滑块
    if (props.lyricText.lrc.lyric.split(/\[.*\]/).length > 9) {
      const top = e.screenY - 732;
      const topLength = 260 - (260 * 260) / pLength;
      // (topLength,top,pLength)
      if (top > topLength) {
        setScrolHeight(topLength);
      } else {
        setScrolHeight(e.screenY - 732);
      }
      scrollRef.current.scrollTop =
        pLength * (top / topLength) - 110 > 0
          ? pLength * (top / topLength)
          : "";
    }
  };

  const listbdScroll = (e) => {
    //滚动事件,顺便设置滑块
    const h =
      playId === 0
        ? ""
        : props.lyricText.length !== 0
        ? e.target.scrollTop / pLength
        : "";
    const g =
      playId === 0
        ? ""
        : props.lyricText.length !== 0
        ? h * (260 - (260 * 260) / pLength)
        : "";
    setScrolHeight(g);
  };

  return (
    <PlayerWrap>
      <div className="playerBox">
        <div className="playerAutoBox wrap-v2">
          <Control isplaying={isPlaying}>
            <a className="prv playbar_sprite fl" title="上一首(ctrl+←)">
              {" "}
            </a>
            <a
              onClick={(e) => play()}
              className="plv playbar_sprite fl"
              title="播放/暂停(p)"
            >
              {" "}
            </a>
            <a className="nxt playbar_sprite fl" title="下一首(ctrl+→)">
              {" "}
            </a>
          </Control>
          <div className="player-pic-box fl">
            <a className="player-pic playbar_sprite">
              <img
                src={
                  props.playerLists.length == 0
                    ? "https://s4.music.126.net/style/web2/img/default/default_album.jpg"
                    : getSizeImage(
                        props.playLists[0] ? props.playLists[0].al.picUrl : "",
                        34
                      )
                }
                alt=""
              />
              <div href="#/" className="msk">
                {" "}
              </div>
            </a>
          </div>
          <div className="play-mp3 fl">
            <div className="songName">
              {props.playLists.length == 0 ? (
                <span></span>
              ) : (
                <div>
                  <a className="s-n" title={props.playLists[0].name}>
                    {props.playLists[0].name}
                  </a>
                  <a className="zj-name" title={props.playLists[0].ar[0].name}>
                    {props.playLists[0].ar[0].name}
                  </a>
                </div>
              )}
            </div>
            <Slider
              tipFormatter={null}
              value={progress}
              defaultValue={time}
              onChange={sliderChange}
            />
          </div>
          <div className="player-time fl">
            <span className="now-time">{formalMinuteSeconds(time * 1000)}</span>
            <span className="divider">/</span>
            <span className="total-time">
              {formalMinuteSeconds(props.times)}
            </span>
          </div>
          <div className="play-right-func fl">
            <a className="player-list fl"> </a>
            <a className="player-add fl playbar_sprite"> </a>
            <a className="player-forw fl playbar_sprite"> </a>
          </div>
          <div className="player-line playbar_sprite fl"></div>
          <div className="player-right-vxl fl">
            <a className="player-voice playbar_sprite fl"> </a>
            <a className="player-loop playbar_sprite fl"> </a>
            <a
              className="player-lists playbar_sprite fl"
              onClick={checkShowSongList}
            >
              {props.songListsAll.length}
            </a>
          </div>
          <div
            className={classnames({ isShow: showSongList, songListBox: true })}
          >
            <div className="listhd playlist_bg">
              <div className="listhdc">
                <h4>
                  播放列表({props.songListsAll ? props.songListsAll.length : 0})
                </h4>
                <a className="addall" href="#/">
                  <span className="ico playlistP ico-add"></span>
                  收藏全部
                </a>
                <a onClick={props.clearAll} className="clearAll" href="#/">
                  <span className="ico ico-clear playlistP"></span>
                  清除
                </a>
                <p className="lytit f-ff0 f-thide j-flag"></p>
                <span
                  onClick={() => setShowSongList(false)}
                  className="close playlistP"
                >
                  关闭
                </span>
              </div>
            </div>
            <div className="listbd playlist_bg">
              <div className="listbd-left">
                {props.arrId.length === 0 || props.arrId === 0 ? (
                  <div className="nosong">
                    <i className="ico playlistP ico-face"></i>
                    你还没有添加任何歌曲
                    <br />
                    去首页<a href="#/">发现音乐</a>,或在
                    <a href="#/">我的音乐</a>收听自己收藏的歌单
                    <div className="splitD"></div>
                  </div>
                ) : (
                  <div className="song">
                    <ul>
                      {props.songListsAll.map((item, index) => {
                        const showPlay = item.id == clickId;
                        return (
                          <li
                            className={classnames({ showPlay: showPlay })}
                            key={item.id}
                            onClick={(e) => mouseClick(item.id)}
                          >
                            <div className="songPlay">
                              <div
                                className={classnames({
                                  songPlayIcn: true,
                                  showPlay: showPlay,
                                })}
                              ></div>
                            </div>
                            <div className="songName">{item.name}</div>
                            <div className="song-icon">
                              <div className={classnames({ iconFour: true })}>
                                <i
                                  className="icon playlistP icon-del"
                                  onClick={(e) => props.deleteId(e, item.id)}
                                  title="删除"
                                >
                                  删除
                                </i>
                                <i
                                  className="icon playlistP icon-dl"
                                  title="下载"
                                >
                                  下载
                                </i>
                                <i
                                  className="icon playlistP icon-share"
                                  title="分享"
                                >
                                  分享
                                </i>
                                <i
                                  className="icon playlistP icon-add"
                                  title="收藏"
                                >
                                  收藏
                                </i>
                              </div>
                            </div>
                            <div className="song-artist">
                              <span>
                                {item.ar.map((itema, indexa) => {
                                  return (
                                    <a
                                      key={indexa}
                                      href="#/"
                                      title={item.ar.map((itemb, indexb) => {
                                        return itemb.name;
                                      })}
                                    >
                                      {indexa + 1 === item.ar.length
                                        ? itema.name
                                        : itema.name + "/"}
                                    </a>
                                  );
                                })}
                              </span>
                            </div>
                            <div className="song-time">
                              {formalMinuteSeconds(item.dt)}
                            </div>
                            <div className="song-lj">
                              <a className="playlistP" href="#/">
                                {" "}
                              </a>
                            </div>
                          </li>
                        );
                      })}
                    </ul>
                  </div>
                )}
              </div>
              <div
                ref={scrollRef}
                onScrollCapture={(e) => listbdScroll(e)}
                className="listbd-right"
              >
                <div className="listbd-ab" ref={listbdRef}>
                  {playId === 0
                    ? ""
                    : props.lyricText.length !== 0
                    ? props.lyricText.lrc.lyric
                        .split("\n")
                        .map((item, index) => {
                          return (
                            <p
                              key={item}
                              data-id={getMinSecondMsecond(
                                item.split("]")[0].split("[")[1]
                              )}
                            >
                              {item.split(/\[.*\]/)[1]}
                            </p>
                          );
                        })
                    : ""}
                </div>
              </div>
              {playId === 0 ? (
                ""
              ) : props.lyricText.length !== 0 ? (
                <div onClick={listbd} className="listbd-middle">
                  {props.lyricText.lrc.lyric.length > 10 ? (
                    <span
                      style={{
                        height: (260 * 260) / pLength,
                        top: scrolHeight,
                      }}
                      className="scrol"
                    ></span>
                  ) : (
                    ""
                  )}
                </div>
              ) : (
                ""
              )}
            </div>
          </div>
        </div>
      </div>
      <audio ref={audioRef} onTimeUpdate={timeUpdate} />
    </PlayerWrap>
  );
});
